package cn.fraudmetrix.octopus;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author libao.zheng
 * @email libao.zheng@tongdun.net
 * @date 2018/12/26 18:58
 */
public class LockDemo implements Runnable {
    //    private static LockDemo lock = new ReentrantLock();
    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private static java.util.concurrent.locks.Lock readLock = lock.readLock();
    private static java.util.concurrent.locks.Lock writeLock = lock.writeLock();
    private static int i = 0;

    private /**synchronized**/
    void add() {
//        lock.lock();
        writeLock.lock();
        i++;
        try {
            TimeUnit.MILLISECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(i);
//        lock.unlock();
        writeLock.unlock();
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        LockDemo demo = new LockDemo();
        for (int j = 0; j < 10; j++) {
            executorService.execute(demo);
        }
        executorService.shutdown();

    }

    @Override
    public void run() {
        add();
    }
}
